﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Puzzle.PuzzleService;

namespace Puzzle
{
    public partial class EndGamePage : PhoneApplicationPage
    {
        public EndGamePage()
        {
            InitializeComponent();
            Loaded += EndGamePage_Loaded;
        }

        void EndGamePage_Loaded(object sender, RoutedEventArgs e)
        {
            string time;
            NavigationContext.QueryString.TryGetValue("time", out time);
            lblTime.Text = time;
        }

        private void btnSendScore_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtName.Text))
            {
                MessageBox.Show("Digite seu nome.", "Aviso", MessageBoxButton.OK);
                return;
            }
            var player = new Player
            {
                Name = txtName.Text,
                Time = new TimeSpan(0, Convert.ToInt32(lblTime.Text.Split(':')[0]), int.Parse(lblTime.Text.Split(':')[1]))
            };
            PuzzleRakingServiceClient client = new PuzzleRakingServiceClient();
            client.SavePlayerTimeCompleted += client_SavePlayerTimeCompleted;
            client.SavePlayerTimeAsync(player);
        }

        void client_SavePlayerTimeCompleted(object sender, SavePlayerTimeCompletedEventArgs e)
        {
            MessageBox.Show("Dados submetidos com sucesso", "Aviso", MessageBoxButton.OK);
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Tem certeza que deseja sair sem gravar seu recorde, eles serão perdidos", "Aviso", MessageBoxButton.OKCancel);
            if (result.Equals(MessageBoxResult.OK))
            {
                base.OnBackKeyPress(e);
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute)); 
            }
            e.Cancel = true;
        }
    }
}